#!/bin/bash
# MSYS2 下编译thrift脚本
# MSYS2 下载 http://repo.msys2.org/distrib/x86_64/msys2-base-x86_64-20161025.tar.xz

sh_folder=$(dirname $(readlink -f $0))
# 定义编译的版本类型(DEBUG|RELEASE)
build_type=DEBUG
typeset -u arg1=$1
[ "$arg1" = "DEBUG" ] && build_type=$arg1
[ "$arg1" = "RELEASE" ] && build_type=$arg1

gcc_version=$(gcc -dumpversion)
gcc_version=${gcc_version//./}

echo build_type=$build_type
pushd $sh_folder

# 安装依赖库和必须的工具
#pacman --needed --noconfirm -S unzip bison flex make mingw-w64-x86_64-openssl \
#            mingw-w64-x86_64-boost mingw-w64-x86_64-cmake \
#            mingw-w64-x86_64-toolchain mingw-w64-x86_64-zlib

thrift_version=0.11.0
thrift_chksum=a325a1e2b257e2fbd1d36cd5c5a7fbe2
thrift_package=thrift-$thrift_version.zip
## 下载源码
if [ ! -f "$thrift_package" ]
then 
	need_download=0
else
	# 对于已经存在的文件,判断checksum是否相同,不相同则删除重新下载
	checksum=`md5sum "$thrift_package" | awk '{ print $1 }'`
	[ "$checksum" != "$thrift_chksum" ] && need_download=0 && rm -f "$thrift_package"
	[ "$checksum"  = "$thrift_chksum" ] && need_download=1 
fi
if [ $need_download -eq 0 ]
then 
	wget https://github.com/apache/thrift/archive/$thrift_version.zip -O $thrift_package || exit -1
else
	echo "package $thrift_package exist,skip download" 
fi
###################
folder_name=thrift-$thrift_version

[ -d $folder_name ] && rm -fr $folder_name

## 解压源码
unzip $thrift_package || exit -1

[ -d $folder_name.mingw ] && rm -fr $folder_name.mingw
mkdir $folder_name.mingw 
pushd $folder_name.mingw

cmake -G"MinGW Makefiles" -DCMAKE_MAKE_PROGRAM=/mingw64/bin/mingw32-make \
	 -DCMAKE_BUILD_TYPE=$build_type \
   -DCMAKE_C_COMPILER=x86_64-w64-mingw32-gcc.exe \
   -DCMAKE_CXX_COMPILER=x86_64-w64-mingw32-g++.exe \
   -DWITH_BOOSTTHREADS=ON \
   -DWITH_LIBEVENT=OFF \
   -DWITH_SHARED_LIB=OFF -DWITH_STATIC_LIB=ON \
   -DWITH_JAVA=OFF -DWITH_PYTHON=OFF \
   -DCMAKE_INSTALL_PREFIX=$sh_folder/dist/thrift-dev/gcc$gcc_version/x64 \
   -DBUILD_TESTING=OFF \
   -DBUILD_TUTORIALS=OFF \
   -DWITH_BOOST_STATIC=ON \
   -DCMAKE_CXX_FLAGS="-static-libgcc -static-libstdc++" \
   ../$folder_name || exit -1
   
cmake --build . --target install -- -j8

popd

popd
